#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <sstream>
#include <fstream>
#include <mysql/mysql.h>
#include <jsoncpp/json/json.h>
#include "logger.hpp"
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

class mysql_util
{
public:
    // 创建mysql句柄、连接服务器、设置客户端字符集
    static MYSQL *mysql_create(const std::string &host, const std::string &username,
        const std::string &password, const std::string &dbname, uint16_t port = 3306)
    {
        // 1. 初始化mysql句柄
        MYSQL *mysql = mysql_init(nullptr);
        if (mysql == nullptr) {
            ELOG("mysql init failed");
            return nullptr;
        }
        if (mysql_real_connect(mysql, host.c_str(), username.c_str(), 
            password.c_str(), dbname.c_str(), port, nullptr, 0) == nullptr) {
            ELOG("connect mysql server failed: %s", mysql_error(mysql));
            mysql_close(mysql);
            return nullptr;
        }
        if (mysql_set_character_set(mysql, "utf8") != 0) {
            ELOG("set client character failed: %s", mysql_error(mysql));
            mysql_close(mysql);
            return nullptr;
        }
        return mysql;
    }
    // 执行sql语句
    static bool mysql_exec(MYSQL* mysql, const std::string& sql)
    {
        int ret = mysql_query(mysql, sql.c_str());
        if (ret != 0) {
            ELOG("%s", sql.c_str());
            ELOG("mysql query failed: %s", mysql_error(mysql));
            return false;
        }
        return true;
    }
    // 关闭连接，释放句柄
    static void mysql_destory(MYSQL* mysql)
    {
        if (mysql != nullptr) {
            mysql_close(mysql);
        }
    }
};

class json_util
{
public:
    // 序列化
    static bool serialize(const Json::Value &root, std::string &str)
    {
        Json::StreamWriterBuilder swb;
        swb.settings_["emitUTF8"] = true;
        std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
        std::stringstream ss;
        int ret = sw->write(root, &ss);
        if (ret != 0) {
            ELOG("json serialize failed!");
            return false;
        }
        str = ss.str();
        return true;
    }
    // 反序列化
    static bool unserialize(const std::string &str, Json::Value &root)
    {
        Json::CharReaderBuilder crb;
        std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
        std::string errs;
        bool ret = cr->parse(str.c_str(), str.c_str() + str.size(), &root, &errs);
        if (ret == false) {
            ELOG("json unserialize failed: %s", errs.c_str());
            return false;
        }
        return true;
    }
};

class string_util
{
public:
    // 字符串分割
    static int split(const std::string& src, const std::string& sep, std::vector<std::string>& res)
    {
        size_t pos = 0, index = 0;
        while (index < src.size()) {
            pos = src.find(sep, index);
            if (pos ==std::string::npos) {
                res.push_back(src.substr(index));
                break;
            }
            if (pos == index) {
                index += sep.size();
                continue;
            }
            res.push_back(src.substr(index, pos - index));
            index = pos + sep.size();
        }
        return res.size();
    }
};

class file_util
{
public:
    // 读取文件
    static bool read(const std::string& filename, std::string& body)
    {
        // 1. 以二进制的方式打开文件
        std::ifstream ifs(filename, std::ios::binary);
        if (ifs.is_open() == false) {
            ELOG("%s file open failed!", filename.c_str());
            return false;
        }
        // 2. 获取文件大小
        size_t fsize = 0;
        ifs.seekg(0, std::ios::end);
        fsize = ifs.tellg();
        ifs.seekg(0, std::ios::beg);
        body.resize(fsize);
        // 3. 将文件所有数据读取出来
        ifs.read(&body[0], fsize);
        if (ifs.good() == false) {
            ELOG("read %s file content failed!", filename.c_str());
            ifs.close();
            return false;
        }
        // 4. 关闭文件
        ifs.close();
        return true;
    }
};